package com.github.gaojh.aop.proxy;

import cn.hutool.core.util.ReflectUtil;
import com.github.gaojh.aop.AopInfo;
import com.github.gaojh.aop.interceptor.CglibInterceptor;
import net.sf.cglib.proxy.Enhancer;

import java.lang.reflect.Constructor;

/**
 * @author gaojh
 */
public class CglibProxyFactory {

    @SuppressWarnings("unchecked")
    public <T> T proxy(T target, AopInfo aopInfo) {
        final Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(new CglibInterceptor(aopInfo));
        Constructor<?>[] constructors = ReflectUtil.getConstructors(target.getClass());
        Constructor<?> constructor = constructors[0];
        if (constructor.getParameterCount() == 0) {
            return (T) enhancer.create();
        } else {
            return (T) enhancer.create(constructor.getParameterTypes(), new Object[constructor.getParameterCount()]);
        }
    }


}
